import { Button, View, Text, Input } from "@tarojs/components";
import { observer, inject } from "mobx-react";
import React, { useEffect, useState } from "react";
import classNames from "classnames";
import Taro, { useRouter } from "@tarojs/taro";
import {
  entryType,
  ICheckShareInfo,
  IFileShareInfo,
  ISpaceInvitation,
  ISpaceInvitationCompany,
  ISpaceInvitationPartner,
  ISpaceInvitationSpace,
  IUserInfo,
} from "../../../src/interfaces";
import "./index.scss";
import x from "../../assets/x.png";
import { RootStore } from "../../../src/store/root-store";
import {
  getOssUrl,
  setStore,
  setLastInvitation,
  getStore,
  getFromUrl,
} from "../../../src/utils";
import { Image } from "../img";
import {
  CheckCheckShareInfo,
  fetchCheckFileShareInfo,
  fetchCheckShareInfo,
  fetchFileShareInfo,
  fetchinvitation,
  fetchOuterMember,
  fetchUserInfo,
} from "../../../src/api";
import stores from "../store";

interface Props {
  /** 入口类型 */
  type: entryType;
  /** 点击查看 */
  onWatch: () => void;
  rootStore?: RootStore;
}
const Index = (props: Props) => {
  const router = useRouter();
  const { login } = router.params;
  const { type, onWatch, rootStore } = props;
  const [needPassword, setNeedPassword] = useState(
    type === "project" ? true : false
  );
  const [isFocus, setIsFocus] = useState(false);
  const [password, setPassword] = useState("");
  /** 项目邀请信息 */
  const [spaceInfo, setSpaceInfo] = useState<ISpaceInvitation>({
    partner: {},
    reference: {},
    space: {},
  } as ISpaceInvitation);
  const { partner = {}, reference, space = {} } = spaceInfo || {};
  const { teamLogo, partnerLogo, projectName, teamName } =
    partner as ISpaceInvitationPartner;

  const handleInput = (e) => {
    setPassword(e.detail.value);
  };
  const [fileInfo, setFileInfo] = useState<IFileShareInfo | undefined>();
  const [checkInfo, setCheckInfo] = useState<ICheckShareInfo | undefined>();
  const [userInfo, setUserInfo] = useState<IUserInfo>();
  useEffect(() => {
    const projectInit = async () => {
      if (router && router.params && router.params.sign) {
        const { code, data, message } = await fetchinvitation(
          router.params.sign,
          router.params?.referenceId
        );
        setSpaceInfo(data);
        setLastInvitation({
          project: {
            sign: router.params.sign,
            referenceId: router.params?.referenceId,
            projectName: data?.partner.projectName,
          },
        });
        setNeedPassword(data?.space.needPassword);
      }
    };
    const fileInit = async () => {
      if (router && router.params && router.params.shareId) {
        const { code, data, message } = await fetchFileShareInfo(
          router.params.shareId
        );
        setFileInfo(data);
        setNeedPassword(data?.needPassword);
      }
    };
    const checkInit = async () => {
      if (
        router &&
        router.params &&
        router.params.shareId &&
        // router.params.spaceId &&
        router.params.listingId
      ) {
        const { code, data, message } = await fetchCheckShareInfo(
          router.params.spaceId || "sid",
          router.params.listingId,
          router.params.shareId
        );
        if (code !== 0) {
          return;
        }
        setCheckInfo(data);
        setNeedPassword(data?.needPassword);
      }
    };
    const init = async () => {
      /** 邀请信息 */
      const shareInit = async () => {
        if (type === "project") {
          await projectInit();
        } else if (type === "file") {
          await fileInit();
        } else {
          await checkInit();
        }
      };
      /** 用户信息 */
      const userInit = async () => {
        const { code, data, message } = await fetchUserInfo();
        if (code === 0) {
          setUserInfo(data);
        }
      };
      await Promise.all([shareInit(), userInit()]);
      if (login === "true") {
        await handleWatch();
      }
    };
    const token = getStore("token");
    if (!token) {
      setTimeout(() => {
        if ((window as any).tokenPromise) {
          (window as any).tokenPromise.then(() => {
            init();
          });
        } else {
          init();
        }
      }, 100);
    } else {
      init();
    }
    setStore("inviteLink", window.location.href);
  }, []);

  /** 需要登录 */
  const checkIsUserLogin = () => {
    if (!userInfo || !userInfo.user) {
      // 未登录直接到登录页
      const param = getFromUrl(router);
      Taro.navigateTo({
        url: `/pages/project-login/index${param}`,
      });
      return false;
    }
    return true;
  };
  const handleWatch = async () => {
    const referenceId = router?.params?.referenceId || "";
    if (type === "project") {
      const { id } = space as ISpaceInvitationSpace;
      let _paramPassword = "";
      let _paramId = "";
      if (login === "true") {
        _paramPassword = sessionStorage.getItem("project-watch") || "";
        _paramId = sessionStorage.getItem("project-watch-id") || "";
      } else {
        _paramPassword = password;
        _paramId = id;
        sessionStorage.setItem("project-watch", _paramPassword);
        sessionStorage.setItem("project-watch-id", _paramId);
      }
      if (space.needPassword && _paramPassword !== space.password) {
        alert("密码错误");
        return;
      }
      if (!checkIsUserLogin()) return;
      const { code, data, message } = await fetchOuterMember(_paramId, {
        password: _paramPassword,
        referenceId,
      });
      if (code !== 0) {
        if (code !== 1) {
          alert(message);
        }
        return;
      }
      const { companyId, memberType, spaceId } = data;
      Taro.navigateTo({
        url: `/pages/index/index?spaceId=${spaceId}`,
      });
    } else if (type === "file") {
      let _paramPassword = "";
      if (login === "true") {
        _paramPassword = sessionStorage.getItem("file-watch") || "";
      } else {
        _paramPassword = password;
        sessionStorage.setItem("file-watch", password);
      }
      if (fileInfo?.needPassword && _paramPassword !== fileInfo.password) {
        alert("密码错误");
        return;
      }
      if (!checkIsUserLogin()) return;
      const { code, data, message } = await fetchCheckFileShareInfo(
        router?.params?.shareId || "",
        needPassword ? { password: _paramPassword } : {}
      );
      if (code !== 0) {
        if (code !== 1) {
          alert(message);
        }
        return;
      }
      const { accessKey, spaceId, channelId, dirId } = data;
      Taro.navigateTo({
        url: `/pages/file-index/index?shareId=${router?.params?.shareId}&spaceId=${spaceId}&accessKey=${accessKey}&channelId=${channelId}&dirId=${dirId}`,
      });
    } else {
      let _paramId = "";
      let _paramPassword = "";
      if (login === "true") {
        _paramPassword = sessionStorage.getItem("check-watch") || "";
        _paramId = sessionStorage.getItem("check-watch-id") || "";
      } else {
        _paramPassword = password;
        _paramId = checkInfo?.spaceId || "";
        sessionStorage.setItem("check-watch", _paramPassword);
        sessionStorage.setItem("check-spaceid", checkInfo?.spaceId || "");
        sessionStorage.setItem("check-watch-id", _paramId);
      }
      if (checkInfo?.needPassword && _paramPassword !== checkInfo.password) {
        alert("密码错误");
        return;
      }
      if (!checkIsUserLogin()) return;
      const { code, data, message } = await CheckCheckShareInfo(
        _paramId,
        router.params.listingId || "",
        router.params.shareId || "",
        needPassword ? { password: _paramPassword } : {}
      );
      if (code !== 0) {
        if (code !== 1) {
          alert(message);
        }
        return;
      }
      Taro.setStorageSync("accessKey", data?.accessKey);
      const { accessKey, channelId, dirId } = data;
      Taro.navigateTo({
        url: `/pages/check-index/index?spaceId=${checkInfo?.spaceId}&shareId=${router.params.shareId}&listingId=${router.params.listingId}`,
      });
    }
  };
  return (
    <div className="share-card">
      <div
        className={classNames("icons", {
          "no-password": !needPassword,
        })}
      >
        {type === "project" && (
          <>
            <span className="left">
              <Image src={getOssUrl(partnerLogo || {})}></Image>
            </span>
            <span className="middle">
              {/* <span className="iconfont icon-vs"></span> */}
              <img src={x}></img>
            </span>
            <span className="right">
              <Image src={getOssUrl(teamLogo || {})}></Image>
            </span>
          </>
        )}
        {type === "file" && (
          <span className="left">
            <img src={getOssUrl(fileInfo?.company?.logo || {})}></img>
          </span>
        )}
        {type === "check" && (
          <span className="left">
            <Image src={getOssUrl(checkInfo?.company.logo || {})}></Image>
          </span>
        )}
      </div>
      <div className="company-name">
        <span className="ellipsis">
          {type === "project"
            ? teamName
            : type === "file"
            ? fileInfo?.company.name
            : checkInfo?.company.name}
        </span>

        <Text className={classNames("word")}>
          {type === "file" && "分享了"}
          {type === "project" && "邀请您加入"}
          {type === "check" && "邀请您确认"}
        </Text>
      </div>
      <div className="project-name">
        {/* {
          console.log("🚀 ~ file: index.tsx ~ line 300 ~ Index ~ type", type, fileInfo, type === "project"
            ? projectName
            : type === "file"
              ? fileInfo?.name
              : checkInfo?.name || "项目")

        } */}
        {type === "project"
          ? projectName
          : type === "file"
          ? fileInfo?.name || "项目名称"
          : checkInfo?.name || "项目"}
      </div>
      {needPassword && (
        <Input
          className={classNames("password", {
            placeholder: !password,
          })}
          placeholder={isFocus ? "" : "请输入密码"}
          onBlur={() => setIsFocus(false)}
          onFocus={() => setIsFocus(true)}
          value={password}
          onInput={handleInput}
        ></Input>
      )}
      <div className="clearfix">
        <Button
          disabled={!password && needPassword}
          className={classNames("watch", {
            active: !!password || !needPassword,
          })}
          onClick={((!!password || !needPassword) && handleWatch) || undefined}
        >
          立即查看
        </Button>
      </div>
    </div>
  );
};

export const ShareCard = observer(inject("rootStore")(Index));
